#include <iostream>
#include <string>
#include <cstring>
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include "share.hpp"

using namespace std;

inline bool file_exists(const std::string &name)
{
    return (access(name.c_str(), F_OK) != -1);
}

void createNamePipe()
{
    // if (file_exists(namepipe_path))
    //     remove(namepipe_path.c_str());
    if (!file_exists(namepipe_path))
    {
        umask(0);
        int n = mkfifo(namepipe_path.c_str(), mode);
        if (n == -1)
        {
            cout << errno << ": " << strerror(errno) << endl;
            exit(20);
        }
        cout << "Create fifo file success." << endl;
    }
}

void communicate_read(int fd)
{
    char buffer[NUM];
    while (true)
    {
        buffer[0] = 0;
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client# " << buffer << std::endl;
            // printf("%s", buffer);
            fflush(stdout);
        }
        else if (n == 0)
        {
            std::cout << "client quit, me too" << std::endl;
            break;
        }
        else
        {
            std::cout << errno << " : " << strerror(errno) << std::endl;
            break;
        }
    }

    close(fd);

    unlink(namepipe_path.c_str());
}

int main()
{
    // 1.创建命名管道
    createNamePipe();

    // 2.打开管道文件
    int rfd = openFile(namepipe_path, O_RDONLY);

    // 3.通信
    communicate_read(rfd);

    return 0;
}
